package com.rocching.easychat.db;

import android.util.Log;

import com.rocching.easychat.core.UserIdentityContext;
import com.rocching.easychat.entity.DocumentEntity;
import com.rocching.easychat.model.UserModel;
import com.rocching.easychat.util.AppUtil;
import com.rocching.easychat.util.JsonUtil;

import io.rong.imlib.model.UserInfo;

public class LocalUserService extends DocumentService<UserModel> {
    private final String TAG = LocalUserService.class.getName();
    private static LocalUserService instance;

    private LocalUserService() {
        super(DocumentEntity.DOCUMENT_TYPE_USER);
    }

    public static LocalUserService getInstance() {
        if (instance == null) {
            instance = new LocalUserService();
        }
        return instance;
    }

    public void updateUser(UserInfo userInfo) {
        int count = super.update(userInfo.getUserId(), UserModel.class, user -> {
            if (user == null) {
                Log.i(TAG, "the user is null");
                return;
            }
            Log.i(TAG, "the user is " + JsonUtil.toJson(user));
            user.setName(userInfo.getName());
            user.setPhoto(userInfo.getPortraitUri().getPath());
        });

        if (count > 0) {
            UserIdentityContext.update(userInfo);
        }
    }

    public void updateUser(UserModel model) {
        int count = super.update(AppUtil.getTargetUserId(model.getId()), UserModel.class, user -> {
            if (user == null) {
                Log.i(TAG, "the user is null");
                return;
            }
            Log.i(TAG, "the user is " + JsonUtil.toJson(user));
            user.setName(model.getName());
            user.setPhoto(model.getPhoto());
            user.setPhone(model.getPhone());
            user.setRemark(model.getRemark());
        });

        if (count > 0) {
            UserIdentityContext.update(model);
        }
    }

    public void exit() {
        super.deleteAll();
        UserIdentityContext.clear();
    }
}
